package com.qdaily.ui.ui;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.qdaily.supportlibrary.request.JsonData;
import com.qdaily.supportlibrary.util.ImageUtil;
import com.qdaily.supportlibrary.util.LocalDisplay;
import com.qdaily.supportlibrary.util.NetUtil;
import com.qdaily.supportlibrary.util.QDJsonUtil;
import com.qdaily.ui.QDBaseActivity;
import com.qdaily.ui.R;
import com.qdaily.ui.data.DataBase.ReadDAO;
import com.qdaily.ui.data.EventModel.EventCOPChange;
import com.qdaily.ui.data.EventModel.EventQFileDownComplete;
import com.qdaily.ui.net.NetConfigs;
import com.qdaily.ui.net.QDEnum;
import com.qdaily.ui.net.entity.CommentsEntity;
import com.qdaily.ui.net.entity.QuestionDetailsEntity;
import com.qdaily.ui.net.entity.SubmitOptionsEntity;
import com.qdaily.ui.net.model.ArticleMeta;
import com.qdaily.ui.net.model.QuestionDetailOptions;
import com.qdaily.ui.ui.adapter.CommentsAdapter;
import com.qdaily.ui.ui.views.CommentController;
import com.qdaily.ui.ui.views.CommentOrPraiseTextView;
import com.qdaily.ui.ui.views.InputBar;
import com.qdaily.ui.ui.views.QDCommentView;
import com.qdaily.ui.ui.views.QDRefreshCommentView;
import com.qdaily.ui.ui.views.QDWebView.QDArticleWebViewFileCache.QDArticleWebViewFileCacheMgr;
import com.qdaily.ui.ui.views.TitleBar;
import com.qdaily.ui.util.QDUtil;
import com.squareup.otto.Subscribe;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

/**
 * 投票详情
 * Created with IntelliJ IDEA.
 * User: Felix
 * Date: 4/9/15
 * Time: 17:57
 * QQ:74104
 * Email:lovejiuwei@gmail.com
 */
public class VotingDetailsActivity extends QDBaseActivity implements View.OnClickListener {
    public final static String KEY_REQUEST_VOTING_DETAILS = "VotingDetailsActivity-REQUEST_VOTING_DETAILS_KEY";
    public final static String KEY_REQUEST_VOTE_ID = "KEY_REQUEST_VOTE_ID";
    public final static String KEY_REQUEST_FROMUSER = "KEY_REQUEST_FromUser";

    private ArticleMeta articleMeta;
    private int voteId;
    private boolean fromUserInfo;
    private QuestionDetailsEntity questionDetailsEntity;
    private TitleBar viewTitleHeaderBar;

    private boolean isRunning = false;

    //options
    private android.widget.LinearLayout linearLayoutVotingDetailsOptions;
    private View votingDetailsSend;
    private ImageView votingDetailsSend_img;

    private HashSet<Integer> result;
    private List<OptionData> optionDatas;

    //top show
    private RelativeLayout relativeLayoutResearchListViewItemContainer;
    private ImageView cubeImageViewResearchLogo;
    private TextView textViewResearchItemRecordCount;
    private TextView textViewResearchTitle;
    private TextView textViewResearchContent;

    //comments
    private CommentsEntity commentsEntity;
    private CommentOrPraiseTextView textViewVotingDetailsCommentCount;
    private View joinView;
    private View joinNew;

    //toolbar
    private InputBar inputBar;

    //comments listview
    private QDCommentView mCommentView;
    private CommentsAdapter commentsAdapter;
    private CommentController commentController;

    //headerview
    private View headerView = null;

    private List<GifImageView> optionGifImageViewList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_voting_details);

        this.articleMeta = getIntent().getParcelableExtra(KEY_REQUEST_VOTING_DETAILS);
        this.voteId = getIntent().getIntExtra(KEY_REQUEST_VOTE_ID, -1);
        {
            Uri mData = getIntent().getData();
            if (mData != null && mData.getHost() != null && mData.getHost().equals(getString(R.string.ias_type_paper))) {
                voteId = Integer.valueOf(mData.getPath().replace("/", ""));
            }
        }

        if (articleMeta == null && voteId == -1) {
            return;
        }

        if (articleMeta != null) {
            voteId = articleMeta.getPost().getId();
        }

        fromUserInfo = getIntent().getBooleanExtra(KEY_REQUEST_FROMUSER, false);

        initViewRes();
        requestVotingDetails();
        commentController.loadData(mCommentView);
        ReadDAO.getInstance().read(voteId, QDEnum.DetailEnum.VOTE.value);
    }

    private void initViewRes() {
        this.viewTitleHeaderBar = (TitleBar) findViewById(R.id.viewTitleHeaderBar);
        viewTitleHeaderBar.getImageViewTitleBarLeft().setVisibility(View.GONE);

        this.mCommentView = (QDCommentView) findViewById(R.id.vote_commentview);

        this.headerView = LayoutInflater.from(this).inflate(R.layout.view_voting_details_headerview, null);
        this.mCommentView.addHeaderView(headerView);

        this.commentsAdapter = new CommentsAdapter(this, mCommentView);
        this.mCommentView.setAdapter(commentsAdapter);

        //headerView
        votingDetailsSend = headerView.findViewById(R.id.votingDetailsSend);
        votingDetailsSend_img = (ImageView) headerView.findViewById(R.id.votingDetailsSend_img);
        this.linearLayoutVotingDetailsOptions = (LinearLayout) headerView.findViewById(R.id.linearLayoutVotingDetailsOptions);
        this.relativeLayoutResearchListViewItemContainer = (RelativeLayout) headerView.findViewById(R.id.relativeLayoutResearchListViewItemContainer);
        this.cubeImageViewResearchLogo = (ImageView) headerView.findViewById(R.id.cubeImageViewResearchLogo);
        this.textViewResearchItemRecordCount = (TextView) headerView.findViewById(R.id.textViewResearchItemRecordCount);
        this.textViewResearchTitle = (TextView) headerView.findViewById(R.id.textViewResearchTitle);
        this.textViewResearchContent = (TextView) headerView.findViewById(R.id.textViewResearchContent);
        this.textViewVotingDetailsCommentCount = (CommentOrPraiseTextView) headerView.findViewById(R.id.textViewVotingDetailsCommentCount);
        this.joinView = headerView.findViewById(R.id.textViewResearchDes);
        this.joinNew = headerView.findViewById(R.id.imageViewResearchNew);
        headerView.findViewById(R.id.cubeImageViewResearchCategory).setVisibility(View.GONE);
        this.votingDetailsSend.setOnClickListener(this);
        votingDetailsSend.setVisibility(View.GONE);
        votingDetailsSend.setEnabled(false);
        votingDetailsSend_img.setAlpha(0.5f);

        int defaultPadding = getResources().getDimensionPixelOffset(R.dimen.article_paddingLeft);
        textViewResearchTitle.setPadding(defaultPadding, 0, defaultPadding, 0);
        textViewResearchTitle.setTextColor(getResources().getColor(R.color.black));
        textViewResearchTitle.setTextSize(LocalDisplay.px2sp(getResources().getDimension(R.dimen.vote_detail_title_textSize)));
        textViewResearchTitle.setMaxLines(10);

        textViewResearchContent.setPadding(defaultPadding, 0, defaultPadding, 0);
        textViewResearchContent.setTextColor(getResources().getColor(R.color.vote_detail_content_textColor));
        textViewResearchContent.setTextSize(LocalDisplay.px2sp(getResources().getDimension(R.dimen.vote_detail_content_textSize)));
        textViewResearchContent.setMaxLines(100);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) textViewResearchContent.getLayoutParams();
        lp.setMargins(0, LocalDisplay.dp2px(10), 0, 0);
        textViewResearchContent.setLayoutParams(lp);

        inputBar = new InputBar(this, R.id.vote_inputbar, false);
        inputBar.setInputBarType(voteId, QDEnum.DetailEnum.VOTE);

        this.commentController = new CommentController(this, commentsAdapter, inputBar,
                voteId,
                QDEnum.DetailEnum.VOTE);

        ViewGroup.MarginLayoutParams vl = (ViewGroup.MarginLayoutParams) relativeLayoutResearchListViewItemContainer.getLayoutParams();
        vl.setMargins(0, 0, 0, 0);
        this.relativeLayoutResearchListViewItemContainer.setLayoutParams(vl);

        //因为模板已经有些可以复用的信息，预加载待回调回来再更新。
        if (articleMeta != null) {
            inputBar.setCommentCount(articleMeta.getPost().getComment_count());
            inputBar.setPraiseCount(articleMeta.getPost().getPraise_count());
            displayPreloadData(articleMeta);
        }
    }

    private void requestVotingDetails() {
        if (fromUserInfo)
        {
            getRequestManager().requestUserQuestionDetail(voteId);
        } else
        {
            getRequestManager().requestQuestionnaireDetail(voteId);
        }
    }

    @Override
    protected void onRequestCallBack(NetUtil.NetParams params, JsonData response) {
        super.onRequestCallBack(params, response);
        if (params instanceof NetConfigs.RequestQuestionnaireDetail || params instanceof NetConfigs.RequestUserQuestionDetail) {
            questionDetailsEntity = QDJsonUtil.Json2Object(response.toString(), QuestionDetailsEntity.class);
            if (questionDetailsEntity.getResponse() != null) {
                displayResponseData(questionDetailsEntity);
                commentController.setArticleInfoShare(questionDetailsEntity.getResponse().getShare());
            } else {
                displayToast(questionDetailsEntity.getMeta() != null ? questionDetailsEntity.getMeta().getMsg() : getText(R.string.article_error_toast).toString());
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
            }
        } else if (params instanceof NetConfigs.RequestSubmitOptions) {
            SubmitOptionsEntity submitOptionsEntity = QDJsonUtil.Json2Object(response.toString(), SubmitOptionsEntity.class);
            displayToast(submitOptionsEntity.getMeta().getMsg());
            Intent intent = new Intent(this, MyAttitudeActivity.class);
            intent.putExtra(MyAttitudeActivity.EXTRA_ATTITUDE_DISPLAY, submitOptionsEntity.getResponse());
            intent.putExtra(MyAttitudeActivity.EXTRA_ATTITUDE_COMMENTS_DISPLAY, voteId);
            intent.putExtra(MyAttitudeActivity.EXTRA_ATTITUDE_LIKED_DISPLAY, questionDetailsEntity.getResponse().getPost().getPraise_count());
            startActivity(intent);
        }
    }

    @Override
    public void onRequestErrorCallBack(NetUtil.NetParams params, Object response) {
        if (params instanceof NetConfigs.RequestQuestionnaireDetail) {
            displayToast(getText(R.string.article_error_toast).toString());
            Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    finish();
                }
            }, 1000);
        }
    }

    private void displayPreloadData(ArticleMeta articleMeta) {
        viewTitleHeaderBar.setTitle(articleMeta.getPost().getCategory().getTitle());
        ImageUtil.getInstance().displayImage(articleMeta.getPost().getImage(), cubeImageViewResearchLogo);
        textViewResearchTitle.setText("" + articleMeta.getPost().getTitle());
        textViewResearchContent.setText("" + articleMeta.getPost().getDescription());
        if (articleMeta.getPost().getComment_count() != 0)
        {

        }
        textViewVotingDetailsCommentCount.setCommentTotalNum(articleMeta.getPost().getComment_count());

        if (QDUtil.isToday(articleMeta.getPost().getPublish_time())) {
            joinNew.setVisibility(View.VISIBLE);
            textViewResearchItemRecordCount.setVisibility(View.GONE);
            joinView.setVisibility(View.GONE);
        } else {
            joinNew.setVisibility(View.GONE);
            textViewResearchItemRecordCount.setVisibility(View.VISIBLE);
            joinView.setVisibility(View.VISIBLE);
            textViewResearchItemRecordCount.setText("" + articleMeta.getPost().getRecord_count());
        }
    }

    private void displayResponseData(QuestionDetailsEntity questionDetailsEntity) {
        viewTitleHeaderBar.setTitle(questionDetailsEntity.getResponse().getPost().getCategory().getTitle());
        ImageUtil.getInstance().displayImage(questionDetailsEntity.getResponse().getPost().getImage(), cubeImageViewResearchLogo);
        textViewResearchTitle.setText("" + questionDetailsEntity.getResponse().getPost().getTitle());
        textViewResearchContent.setText("" + questionDetailsEntity.getResponse().getPost().getDescription());

        textViewVotingDetailsCommentCount.setCommentTotalNum(questionDetailsEntity.getResponse().getPost().getComment_count());

        if (QDUtil.isToday(questionDetailsEntity.getResponse().getPost().getPublish_time())) {
            joinNew.setVisibility(View.VISIBLE);
            textViewResearchItemRecordCount.setVisibility(View.GONE);
            joinView.setVisibility(View.GONE);
        } else {
            joinNew.setVisibility(View.GONE);
            textViewResearchItemRecordCount.setVisibility(View.VISIBLE);
            joinView.setVisibility(View.VISIBLE);
            textViewResearchItemRecordCount.setText("" + questionDetailsEntity.getResponse().getPost().getRecord_count());
        }

        inputBar.setCommentCount(questionDetailsEntity.getResponse().getPost().getComment_count());
        inputBar.setPraiseCount(questionDetailsEntity.getResponse().getPost().getPraise_count());
        votingDetailsSend.setVisibility(View.VISIBLE);

        // options
        // 这里questions会含有多个问题。问题里又包括content & id & options
        optionGifImageViewList = new ArrayList<>();
        int questionSize = questionDetailsEntity.getResponse().getQuestions().size();
        result = new HashSet<>();
        optionDatas = new ArrayList<>();

        for (int i = 0; i < questionSize; i++) {
            int optionsSize = questionDetailsEntity.getResponse().getQuestions().get(i).getOptions().size();
            isSingleOption = questionDetailsEntity.getResponse().getQuestions().get(i).getGenre() != 2; //不等于2就是单选
            for (int j = 0; j < optionsSize; j++) {
                //find the data model
                final QuestionDetailOptions questionDetailQuestions = questionDetailsEntity.getResponse().getQuestions().get(i).getOptions().get(j);
                //inflate view
                View votingDetailsOptionsItem = LayoutInflater.from(this).inflate(R.layout.view_voting_details_options, null);
                GifImageView gifImageViewVotingDetailsOptionsIcon = (GifImageView) votingDetailsOptionsItem.findViewById(R.id.gifImageViewVotingDetailsOptionsIcon);
                TextView textViewVotingDetailsOptionsContent = (TextView) votingDetailsOptionsItem.findViewById(R.id.textViewVotingDetailsOptionsContent);
                ImageView checkboxVotingDetailsOptionsSelected = (ImageView) votingDetailsOptionsItem.findViewById(R.id.checkboxVotingDetailsOptionsSelected);
                //set value
                textViewVotingDetailsOptionsContent.setText(questionDetailQuestions.getContent());

                gifImageViewVotingDetailsOptionsIcon.setTag(questionDetailQuestions.getImage());
                optionGifImageViewList.add(gifImageViewVotingDetailsOptionsIcon);
                File file = QDArticleWebViewFileCacheMgr.getInstance().getLocalGifCache(questionDetailQuestions.getImage());
                if (file != null) {
                    gifImageViewVotingDetailsOptionsIcon.setImageURI(Uri.fromFile(file));
                }

                OptionData optionData = new OptionData();
                optionData.optionId = questionDetailQuestions.getId();
                optionData.optionNum = j;
                optionData.checkBox = checkboxVotingDetailsOptionsSelected;
                votingDetailsOptionsItem.setId(R.id.vote_options_view);
                votingDetailsOptionsItem.setTag(j);
                optionDatas.add(optionData);

                votingDetailsOptionsItem.setOnClickListener(this);
                checkboxVotingDetailsOptionsSelected.setEnabled(false);
                //add to root view
                linearLayoutVotingDetailsOptions.addView(votingDetailsOptionsItem);
                if (fromUserInfo)
                {
                    if (questionDetailQuestions.isSelected())
                    {
                        onClick(votingDetailsOptionsItem);
                    }
                }
            }
        }

        //toolbar
        inputBar.setCommentCount(questionDetailsEntity.getResponse().getPost().getComment_count());
        inputBar.setPraiseCount(questionDetailsEntity.getResponse().getPost().getPraise_count());
    }

    private boolean isSingleOption = true; //是不是单选

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.votingDetailsSend:
                String options = "";
                Iterator iter = result.iterator();
                while (iter.hasNext()) {
                    int value = (int) iter.next();
                    options += value + ",";
                }
                if (!TextUtils.isEmpty(options)) {
                    getRequestManager().requestSubmitOptions(questionDetailsEntity.getResponse().getPost().getId(), options);
                } else {
                    displayToast(R.string.at_least_one);
                }
                break;
            case R.id.vote_options_view:
                int optionNum = (int) v.getTag();
                if (isSingleOption) //单选肯定只有1个
                {
                    result.clear();
                    for (int i = 0; i < optionDatas.size(); i++) {
                        if (i != optionNum) {
                            OptionData data = optionDatas.get(i);
                            data.checkBox.setSelected(false);
                        }
                    }

                    OptionData optionData = optionDatas.get(optionNum);
                    optionData.checkBox.setSelected(!optionData.checkBox.isSelected());
                    if (optionData.checkBox.isSelected()) {
                        result.add(optionData.optionId);
                    }
                } else {
                    OptionData optionData = optionDatas.get(optionNum);
                    if (result.contains(optionData.optionId)) {
                        result.remove(optionData.optionId);
                        optionData.checkBox.setSelected(false);
                    } else {
                        result.add(optionData.optionId);
                        optionData.checkBox.setSelected(true);
                    }
                }
                if (result != null && result.size() > 0)
                {
                    votingDetailsSend.setEnabled(true);
                    votingDetailsSend_img.setAlpha(1.0f);
                }
                else
                {
                    votingDetailsSend.setEnabled(false);
                    votingDetailsSend_img.setAlpha(0.5f);
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (optionGifImageViewList != null) {
            for (GifImageView gifImageView : optionGifImageViewList) {
                Drawable drawable = gifImageView.getDrawable();
                if (drawable instanceof GifDrawable) {
                    gifImageView.setImageBitmap(null);
                    gifImageView.setImageDrawable(null);
                    ((GifDrawable) drawable).recycle();
                }
            }
        }
        super.onDestroy();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Subscribe
    public void receiveCOPDataChane(EventCOPChange event) {
        if ((event.getType() == QDEnum.DetailEnum.VOTE || event.getType() == QDEnum.DetailEnum.VOTERESULT) && event.getId() == voteId) {
            if (event.getCommentCount() != -1) //评论个数不分是不是子评论
            {
                textViewVotingDetailsCommentCount.setCommentTotalNum(event.getCommentCount());
                inputBar.setCommentCount(event.getCommentCount());
            }
        }
    }

    @Subscribe
    public void receiveFileDownComplete(EventQFileDownComplete event) {
        if (event.getUrl() != null && event.isSuccess()) {
            if (optionGifImageViewList != null) {
                for (GifImageView gifImageView : optionGifImageViewList) {
                    String url = (String) gifImageView.getTag();
                    if (url.equals(event.getUrl())) {
                        gifImageView.setImageURI(Uri.fromFile(new File(event.getFilePath(), event.getName())));
                        break;
                    }
                }
            }
        }
    }

    class OptionData {
        int optionNum;
        int optionId;
        ImageView checkBox;
    }
}
